var util = require('util');
var fs = require('fs');
require('buffer');

var express = require('express');
var mongoose = require('mongoose');
var mongoStore = require('connect-mongodb');

var taskManager = require('./TaskManager');
var logManager = require('./LogManager');
var auth = require('./Middleware/Authenticate');
var access = require('./Middleware/Access');

log = new logManager({display : 2, level: 2});

//fs.open('./errors.log', "w", function(e, fd) {
//	process.on('uncaughtException', function (e) {
//		util.puts("UNCAUGHT ERROR:\r\n" + e.message);
//		var error = new buffer(Date.now() + ": " + e.message + "\r\n" + e.stack + "\r\n\r\n");
//		fs.write(fd, error, 0, error.length, null);
//	});
//});

// Mongoose Connection
model = {};
mongoose.connect('mongobd://127.0.0.1/controls2');

// Express Router
app = express.createServer();
app.configure(function() {
	app.set('views', __dirname + '/Views');
	app.use(express.bodyParser());
	app.use(express.methodOverride());
	app.use(express.cookieParser());
//	app.use(express.session({
//		store : new mongoStore({
//			db : mongoose.conection
//		}),
//		secret : 'kD7Mde3$gHf^D'
//	}));
//	app.use(auth.user());
	app.use(app.router);
	//app.use(express.static(__dirname + '/static'));
});

app.on('error', function(e) {
	
});

// Task Manager
tasks = new taskManager();

// Models
require('./Models/Port2');
require('./Models/Device2');
//require('./Models/Link');

// Controls
require('./Controls/Default');
require('./Controls/Devices');
require('./Controls/Ports');
require('./Controls/ajax');
//require('./Controls/Links');

tasks.on('link_update', function(id, value) {
	log.debug("Updating Link " + id + " = " + value);
});

app.get('/static/*', function(req, res) {
	var pathParts = req.path.match(/\/static\/(.*)/i) || [];
	
	if(pathParts.length == 2) {
		var staticPath = __dirname + "/static/" + pathParts[1];
		console.log("Static Path: " + staticPath);
		
		fs.stat(staticPath, function(err, stat) {
			if(err || stat.isDirectory()) {
				res.send("404 File Not Found!", 404);
			} else {
				var stream = fs.createReadStream(staticPath);
			    req.emit('static', stream);
			    stream.pipe(res);
			}
		});
	} else {
		res.send("404 File Not Found!", 404);
	}
});

app.listen(8080);
